package com.yiyuzi.admin.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiyuzi.admin.common.domain.PageResultDTO;
import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yiyuzi
 * @date 2021/5/7 16:14
 */

public class ConvertUtils {
    public static <T> PageResultDTO<T> convertPageResult(){
        return convertPageResult(new Page<>());
    }

    public static <T> PageResultDTO<T> convertPageResult(IPage<T> page){
        PageResultDTO<T> resultDTO = new PageResultDTO<>();
        resultDTO.setPageNum(page.getCurrent());
        resultDTO.setPageSize(page.getSize());
        resultDTO.setTotal(page.getTotal());
        resultDTO.setPages(page.getPages());
        resultDTO.setList(page.getRecords());
        return resultDTO;
    }

    public static <T, E> PageResultDTO<T> convertPageResult(List<E> sourceList, Class<T> tClass){
        return convertPageResult(new Page<>(), sourceList, tClass);
    }

    public static <T, E> PageResultDTO<T> convertPageResult(IPage page, List<E> sourceList, Class<T> tClass){
        PageResultDTO pageResultDTO = setPage(page);
        List<T> records = copyList(sourceList, tClass);
        page.setRecords(records);
        pageResultDTO.setList(records);
        return pageResultDTO;
    }

    public static <T> T copy(Object source, Class<T> target) {
        if(source == null || target == null){
            return null;
        }
        try {
            T newInstance = target.newInstance();
            BeanUtils.copyProperties(source, newInstance);
            return newInstance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T, K> List<K> copyList(List<T> source, Class<K> target) {
        if (null == source || source.isEmpty()) {
            return Collections.emptyList();
        }
        return source.stream().map(e -> copy(e, target)).collect(Collectors.toList());
    }

    private static PageResultDTO setPage(IPage page) {
        PageResultDTO pageResultDTO = new PageResultDTO();
        pageResultDTO.setPageNum(page.getCurrent());
        pageResultDTO.setPageSize(page.getSize());
        pageResultDTO.setTotal(Long.valueOf(page.getTotal()));
        pageResultDTO.setPages(page.getPages());
        return pageResultDTO;
    }
}

